package com.codebase.zookeeper.zk;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * @describe: 更新节点数据
 */
public class UpdateData implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zk;

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                countDownLatch.countDown();
            }
        }
    }

    /**
     * 同步更新节点数据
     */
    @Test
    public void test1() throws Exception {
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new UpdateData());
        String path = "/root";
        zk.create(path, "111".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println(new String(zk.getData(path, true, null)));

        Stat stat = zk.setData(path, "222".getBytes(), -1);
        System.out.println(stat.getCzxid() + "  " + stat.getMzxid() + "  " + stat.getVersion());

        Stat stat1 = zk.setData(path, "333".getBytes(), stat.getVersion());
        System.out.println(stat1.getCzxid() + "  " + stat1.getMzxid() + "  " + stat1.getVersion());

         try{
            zk.setData(path, "444".getBytes(), stat.getVersion());
         }catch (KeeperException e){
             e.printStackTrace();
         }
        Thread.sleep(3000);

        System.out.println(new String(zk.getData(path, true, null)));
    }

    /**
     * 异步更新节点数据
     */
    @Test
    public void test2() throws Exception{
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new UpdateData());
        String path = "/root";
        zk.create(path, "111".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        zk.setData(path, "222".getBytes(), -1, new StatCallBack(), "ctx");
        Thread.sleep(2000);
    }


    class StatCallBack implements AsyncCallback.StatCallback{
       
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
             System.out.println("rc:"+ rc );
             System.out.println("path:" + path);
             System.out.println("ctx:" + ctx);
             System.out.println(stat.getCzxid() + "  " + stat.getMzxid() + "  "+ stat.getVersion());
        }
    }

}
